package cn.simon.filter;

import cn.simon.util.Site;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.java.Log;

import java.io.IOException;

@Log
//@WebFilter(value = "/*")
public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse resp = (HttpServletResponse)response;
        HttpSession session = req.getSession();
        //获取请求的url
        String url = String.valueOf(req.getRequestURL());
        //如果url包含login,说明此时要去登录，则直接放行
        if(url.contains("login")){
            log.info("不行，被屏蔽了");
            chain.doFilter(request, response);
            return;
        }
        //如果不包含则从session中获取username,如果有username说明已经登录，则放行
        //如果没有则说明没有登录，跳转到登录页面
        String username = (String) session.getAttribute("username");
        if(username==null){
            req.setAttribute("meg","请先登录");
            req.getRequestDispatcher(Site.PREFIX+"/login"+Site.SUFFIX).forward(req,resp);
            return;
        }
        chain.doFilter(request,response);
    }
}
